<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新闻资讯 - 体育比分网</title>
    <script src="../common/js/tailwindcss.js"></script>
    <script src="../common/js/lucide.min.js"></script>
    <style>
        .line-clamp-2 {
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .news-image {
            aspect-ratio: 16/9;
            object-fit: cover;
        }

        .shimmer {
            background: linear-gradient(90deg,
            rgba(207, 216, 220, 0.1),
            rgba(207, 216, 220, 0.3),
            rgba(207, 216, 220, 0.1));
            background-size: 200% 100%;
            animation: shimmer 1.5s infinite;
        }

        @keyframes shimmer {
            0% {
                background-position: -200% 0;
            }
            100% {
                background-position: 200% 0;
            }
        }
    </style>
</head>
<body class="min-h-screen bg-gray-100">
<!-- 主导航栏 -->
<nav class="bg-white shadow-md sticky top-0 z-40">
    <div class="max-w-7xl mx-auto px-4">
        <!-- 上层导航 - Logo和用户功能区 -->
        <div class="flex justify-between items-center h-16">
            <div class="flex items-center">
                <button onclick="window.location.href='/'" class="p-2 rounded-md hover:bg-gray-100">
                    <i data-lucide="arrow-left"></i>
                </button>
                <span class="ml-4 text-xl font-bold">体育比分网</span>
            </div>
            <div class="flex items-center space-x-4">
                <i data-lucide="search"></i>
                <i data-lucide="bell"></i>
                <i data-lucide="user"></i>
            </div>
        </div>

        <!-- 下层导航 - 主要功能区 -->
        <div class="flex items-center space-x-6 h-12 text-gray-600">
            <a href="/"
               class="flex items-center h-full border-b-2 border-transparent hover:text-blue-500 hover:border-blue-500 px-1">
                比分直播
            </a>
            <a href="/video/video.html"
               class="flex items-center h-full border-b-2 border-transparent hover:text-blue-500 hover:border-blue-500 px-1">
                <i data-lucide="play" class="w-4 h-4 mr-1"></i>
                视频集锦
            </a>
            <a href="/news/news.html"
               class="flex items-center h-full border-b-2 border-blue-500 text-blue-500 px-1">
                <i data-lucide="newspaper" class="w-4 h-4 mr-1"></i>
                新闻资讯
            </a>
        </div>
    </div>
</nav>

<main class="max-w-7xl mx-auto px-4 py-6">
    <!-- 语言切换 -->
    <div class="flex justify-between items-center mb-6">
        <div class="flex space-x-2">
            <button onclick="changeLanguage('zh')"
                    id="langZh"
                    class="flex items-center px-3 py-1 rounded-lg text-sm transition-colors bg-gray-100 text-gray-700">
                🇨🇳 中文
            </button>
            <button onclick="changeLanguage('en')"
                    id="langEn"
                    class="flex items-center px-3 py-1 rounded-lg text-sm transition-colors bg-blue-500 text-white">
                🇬🇧 English
            </button>
            <button onclick="changeLanguage('th')"
                    id="langTh"
                    class="flex items-center px-3 py-1 rounded-lg text-sm transition-colors bg-gray-100 text-gray-700">
                🇹🇭 ไทย
            </button>
        </div>

        <!-- 搜索框 -->
        <div class="relative">
            <input type="text"
                   id="searchInput"
                   placeholder="搜索新闻..."
                   class="pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"/>
            <i data-lucide="search"
               class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4"></i>
        </div>
    </div>

    <!-- 新闻分类 -->
    <div class="flex flex-wrap gap-2 mb-6">
        <button onclick="filterNews('all')"
                id="categoryAll"
                class="px-4 py-2 rounded-lg transition-colors bg-blue-500 text-white">
            全部
        </button>
        <button onclick="filterNews('football')"
                id="categoryFootball"
                class="px-4 py-2 rounded-lg transition-colors bg-white text-gray-600 hover:bg-gray-50">
            足球
        </button>
        <button onclick="filterNews('basketball')"
                id="categoryBasketball"
                class="px-4 py-2 rounded-lg transition-colors bg-white text-gray-600 hover:bg-gray-50">
            篮球
        </button>
        <button onclick="filterNews('baseball')"
                id="categoryBaseball"
                class="px-4 py-2 rounded-lg transition-colors bg-white text-gray-600 hover:bg-gray-50">
            棒球
        </button>
    </div>

    <!-- 内容区域 -->
    <div class="relative">
        <!-- 新闻列表 -->
        <div id="newsList" class="space-y-6"></div>

        <!-- 在新闻列表下方添加分页容器 -->
        <div id="pagination" class="mt-6"></div>

        <!-- 加载状态 -->
        <div id="loading" class="space-y-6">
            <!-- 加载骨架屏 -->
            <div class="bg-white rounded-lg shadow p-4">
                <div class="flex space-x-4">
                    <div class="w-48 h-32 bg-gray-200 rounded-lg shimmer"></div>
                    <div class="flex-1">
                        <div class="h-6 bg-gray-200 rounded w-3/4 mb-2 shimmer"></div>
                        <div class="h-4 bg-gray-200 rounded w-full mb-2 shimmer"></div>
                        <div class="h-4 bg-gray-200 rounded w-2/3 shimmer"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
    // 全局变量
    let currentLanguage = 'en';
    let currentCategory = 'all';
    let allNews = [];
    let displayedNews = [];
    const API_KEY = 'ff6dbedc167d41e6ba5beb0fe440ec52'; // 替换为你的 NewsAPI 密钥

    // 语言配置
    const LANGUAGES = {
        zh: {
            searchPlaceholder: '搜索新闻...',
            loadMore: '加载更多',
            noNews: '暂无相关新闻',
            error: '加载失败，请稍后重试',
            readMore: '阅读更多',
            prevPage: '上一页',
            nextPage: '下一页',
            totalResults: '共 ${total} 条新闻',
            currentPage: '第 ${current}/${total} 页'
        },
        en: {
            searchPlaceholder: 'Search news...',
            loadMore: 'Load More',
            noNews: 'No news available',
            error: 'Failed to load, please try again later',
            readMore: 'Read More',
            prevPage: 'Previous',
            nextPage: 'Next',
            totalResults: 'Total ${total} news',
            currentPage: 'Page ${current}/${total}'
        },
        th: {
            searchPlaceholder: 'ค้นหาข่าว...',
            loadMore: 'โหลดเพิ่มเติม',
            noNews: 'ไม่มีข่าว',
            error: 'โหลดไม่สำเร็จ กรุณาลองใหม่อีกครั้ง',
            readMore: 'อ่านเพิ่มเติม',
            prevPage: 'ก่อนหน้า',
            nextPage: 'ถัดไป',
            totalResults: 'ทั้งหมด ${total} ข่าว',
            currentPage: 'หน้า ${current}/${total}'
        }
    };

    // DOM 元素的引用
    let loadingElement;
    let newsListElement;
    let searchInput;

    // 初始化 DOM 引用
    function initDomReferences() {
        loadingElement = document.getElementById('loading');
        newsListElement = document.getElementById('newsList');
        searchInput = document.getElementById('searchInput');
    }

    // 显示/隐藏加载状态
    function toggleLoading(show) {
        if (loadingElement) {
            loadingElement.style.display = show ? 'block' : 'none';
        }
    }

    // 获取新闻数据
    async function fetchNews(page = 1) {
        try {
            const response = await fetch(
                `https://newsapi.org/v2/top-headlines?category=sports&language=${currentLanguage}&pageSize=20&page=${page}&apiKey=${API_KEY}`
            );
            const data = await response.json();

            if (data.status === 'ok') {
                return {
                    articles: data.articles
                        .filter(article => article.title && article.description)
                        .map((article) => ({
                            title: article.title,
                            description: article.description,
                            image: article.urlToImage,
                            url: article.url,
                            publishedAt: article.publishedAt,
                            source: article.source.name,
                            category: getRandomCategory()
                        })),
                    totalResults: data.totalResults // API限制最多100条
                };
            }
            throw new Error('Failed to fetch news');
        } catch (error) {
            console.error('Error fetching news:', error);
            return { articles: [], totalResults: 0 };
        }
    }

    // 随机分配新闻分类
    function getRandomCategory() {
        const categories = ['football', 'basketball', 'baseball'];
        return categories[Math.floor(Math.random() * categories.length)];
    }

    // 格式化时间
    function formatTime(dateStr) {
        const date = new Date(dateStr);
        const now = new Date();
        const diff = now - date;

        if (diff < 3600000) { // 1小时内
            const minutes = Math.floor(diff / 60000);
            return `${minutes}分钟前`;
        } else if (diff < 86400000) { // 24小时内
            const hours = Math.floor(diff / 3600000);
            return `${hours}小时前`;
        } else {
            return date.toLocaleDateString(currentLanguage === 'zh' ? 'zh-CN' : 'en-US', {
                month: 'numeric',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
    }

    // 渲染新闻列表
    function renderNews(newsList) {
        if (!newsListElement) return;

        if (newsList.length === 0) {
            newsListElement.innerHTML = `
            <div class="text-center py-8 text-gray-500">
                ${LANGUAGES[currentLanguage].noNews}
            </div>
        `;
            return;
        }

        newsListElement.innerHTML = newsList
            .filter(news => news.title && news.description)
            .map(news => `
            <div class="bg-white rounded-lg shadow p-4 hover:shadow-md transition-shadow cursor-pointer"
                 onclick="showNewsDetail('${encodeURIComponent(JSON.stringify(news))}')">
                <div class="flex space-x-4">
                    <img src="${news.image || '../../common/images/default-news.png'}"
                         alt="${news.title}"
                         class="w-48 h-32 object-cover rounded-lg"
                         onerror="this.src='../../common/images/default-news.png'"/>
                    <div class="flex-1">
                        <h3 class="font-medium text-lg mb-2 hover:text-blue-600">${news.title}</h3>
                        <p class="text-gray-600 text-sm mb-4 line-clamp-2">
                            ${news.description}
                        </p>
                        <div class="flex items-center justify-between text-sm text-gray-500">
                            <div class="flex items-center space-x-4">
                                <span class="text-blue-500">${news.source}</span>
                                <span>${formatTime(news.publishedAt)}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
    }

    // 显示新闻详情
    function showNewsDetail(newsData) {
        const news = JSON.parse(decodeURIComponent(newsData));
        localStorage.setItem('currentNews', JSON.stringify(news));
        window.location.href = '/news/newsDetail.html';
    }

    // 分页组件
    function createPagination(currentPage, totalPages, totalResults) {
        if (totalResults === 0) {
            return ''; // 如果没有数据，不显示分页
        }

        return `
    <div class="flex flex-col items-center space-y-4 my-8">
        <!-- 添加总条数显示 -->
        <div class="text-sm text-gray-600">
            共 ${totalResults} 条新闻，第 ${currentPage}/${totalPages} 页
        </div>

        <!-- 分页按钮 -->
        <div class="flex justify-center items-center space-x-1">
            <button
                onclick="${currentPage > 1 ? `changePage(${currentPage - 1})` : ''}"
                class="px-4 py-2 text-gray-500 bg-white rounded-lg ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-100'}"
                ${currentPage === 1 ? 'disabled' : ''}
            >
                ${LANGUAGES[currentLanguage].prevPage}
            </button>

            ${generatePageButtons(currentPage, totalPages)}

            <button
                onclick="${currentPage < totalPages ? `changePage(${currentPage + 1})` : ''}"
                class="px-4 py-2 text-gray-500 bg-white rounded-lg ${currentPage === totalPages || totalPages === 0 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-100'}"
                ${currentPage === totalPages || totalPages === 0 ? 'disabled' : ''}
            >
                ${LANGUAGES[currentLanguage].nextPage}
            </button>
        </div>
    </div>`;
    }

    // 生成页码按钮
    function generatePageButtons(currentPage, totalPages) {
        let buttons = [];
        let shouldShowDots = totalPages > 7;

        if (shouldShowDots) {
            if (currentPage <= 4) {
                // 显示前5页、省略号和最后一页
                for (let i = 1; i <= 5; i++) {
                    buttons.push(createPageButton(i, currentPage));
                }
                buttons.push('<span class="px-4 py-2">...</span>');
                buttons.push(createPageButton(totalPages, currentPage));
            } else if (currentPage >= totalPages - 3) {
                // 显示第一页、省略号和最后5页
                buttons.push(createPageButton(1, currentPage));
                buttons.push('<span class="px-4 py-2">...</span>');
                for (let i = totalPages - 4; i <= totalPages; i++) {
                    buttons.push(createPageButton(i, currentPage));
                }
            } else {
                // 显示第一页、省略号、当前页±2、省略号、最后一页
                buttons.push(createPageButton(1, currentPage));
                buttons.push('<span class="px-4 py-2">...</span>');
                for (let i = currentPage - 2; i <= currentPage + 2; i++) {
                    buttons.push(createPageButton(i, currentPage));
                }
                buttons.push('<span class="px-4 py-2">...</span>');
                buttons.push(createPageButton(totalPages, currentPage));
            }
        } else {
            // 总页数<=7时显示所有页码
            for (let i = 1; i <= totalPages; i++) {
                buttons.push(createPageButton(i, currentPage));
            }
        }

        return buttons.join('');
    }

    // 创建单个页码按钮
    function createPageButton(pageNum, currentPage) {
        const isActive = pageNum === currentPage;
        return `
        <button
            onclick="changePage(${pageNum})"
            class="px-4 py-2 rounded-lg ${
            isActive
                ? 'bg-blue-500 text-white'
                : 'text-gray-500 bg-white hover:bg-gray-100'
        }"
        >
            ${pageNum}
        </button>
    `;
    }

    // 切换语言
    async function changeLanguage(lang) {
        currentLanguage = lang;
        const buttons = {
            zh: document.getElementById('langZh'),
            en: document.getElementById('langEn'),
            th: document.getElementById('langTh')
        };

        Object.entries(buttons).forEach(([key, btn]) => {
            if (btn) {
                if (key === lang) {
                    btn.classList.remove('bg-gray-100', 'text-gray-700');
                    btn.classList.add('bg-blue-500', 'text-white');
                } else {
                    btn.classList.remove('bg-blue-500', 'text-white');
                    btn.classList.add('bg-gray-100', 'text-gray-700');
                }
            }
        });

        if (searchInput) {
            searchInput.placeholder = LANGUAGES[lang].searchPlaceholder;
        }

        toggleLoading(true);
        await initNews();
    }

    // 筛选新闻
    function filterNews(category) {
        currentCategory = category;
        const buttons = document.querySelectorAll('[id^="category"]');

        buttons.forEach(btn => {
            if (btn.id === `category${category.charAt(0).toUpperCase() + category.slice(1)}`) {
                btn.classList.remove('bg-white', 'text-gray-600');
                btn.classList.add('bg-blue-500', 'text-white');
            } else {
                btn.classList.remove('bg-blue-500', 'text-white');
                btn.classList.add('bg-white', 'text-gray-600');
            }
        });

        const filtered = category === 'all'
            ? allNews
            : allNews.filter(news => news.category === category);

        renderNews(filtered);
    }

    // 页面切换
    async function changePage(page) {
        try {
            toggleLoading(true);
            const data = await fetchNews(page);
            allNews = data.articles;
            const totalPages = Math.ceil(data.totalResults / 20);

            if (data.articles.length > 0) {
                renderNews(allNews);
            }

            // 更新分页
            const paginationContainer = document.getElementById('pagination');
            if (paginationContainer) {
                paginationContainer.innerHTML = createPagination(page, totalPages, data.totalResults);
            }

            // 平滑滚动到顶部
            window.scrollTo({ top: 0, behavior: 'smooth' });

            toggleLoading(false);
        } catch (error) {
            console.error('Error changing page:', error);
            toggleLoading(false);
        }
    }

    // 搜索防抖
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 搜索新闻
    const searchNews = debounce((searchText) => {
        searchText = searchText.toLowerCase();
        if (searchText === '') {
            displayedNews = currentCategory === 'all'
                ? allNews
                : allNews.filter(news => news.category === currentCategory);
        } else {
            const filtered = allNews.filter(news =>
                (news.title?.toLowerCase().includes(searchText) ||
                    news.description?.toLowerCase().includes(searchText)) &&
                (currentCategory === 'all' || news.category === currentCategory)
            );
            displayedNews = filtered;
        }
        renderNews(displayedNews);
    }, 300);

    // 初始化
    async function initNews() {
        try {
            toggleLoading(true);
            const data = await fetchNews(1);
            allNews = data.articles;
            displayedNews = allNews;
            const totalPages = Math.ceil(data.totalResults / 20);

            if (data.articles.length === 0) {
                if (newsListElement) {
                    newsListElement.innerHTML = `
                    <div class="text-center py-8 text-gray-500">
                        ${LANGUAGES[currentLanguage].noNews}
                    </div>
                `;
                }
            } else {
                renderNews(allNews);
            }

            // 渲染分页
            const paginationContainer = document.getElementById('pagination');
            if (paginationContainer) {
                paginationContainer.innerHTML = createPagination(1, totalPages, data.totalResults);
            }

            toggleLoading(false);
        } catch (error) {
            console.error('Error initializing news:', error);
            toggleLoading(false);
            if (newsListElement) {
                newsListElement.innerHTML = `
                <div class="text-center text-red-500 py-8">
                    ${LANGUAGES[currentLanguage].error}
                </div>
            `;
            }
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        initDomReferences();
        initNews();

        // 添加搜索监听
        if (searchInput) {
            searchInput.addEventListener('input', (e) => {
                searchNews(e.target.value);
            });
        }

        // 初始化图标
        lucide.createIcons();
    });

    // 刷新新闻数据（可选，定时刷新）
    setInterval(() => {
        if (!document.hidden) { // 只在页面可见时刷新
            initNews();
        }
    }, 300000); // 每5分钟刷新一次
</script>
</body>
</html>

